package com.rbmh.network.utils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;

import java.io.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WordDocumentHandlerX {

    // 省略其他方法...

    /**
     * 查找特定格式的文本，提取数字并加1
     * @param filePath 文档路径
     * @param pattern 正则表达式模式，用于匹配和提取数字
     */
    public static void incrementNumberInPattern(String filePath, String pattern) {
        try {
            if (isDocxFormat(filePath)) {
                incrementNumberInDocx(filePath, pattern);
            } else {
                System.out.println("此功能仅支持 .docx 格式");
            }
        } catch (IOException e) {
            System.err.println("修改文档时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 在 .docx 文档中查找模式并递增数字
     */
    private static void incrementNumberInDocx(String filePath, String regexPattern) throws IOException {
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {

            boolean modified = false;
            Pattern pattern = Pattern.compile(regexPattern);

            // 在段落中查找并修改
            for (XWPFParagraph para : document.getParagraphs()) {
                String text = para.getText();
                Matcher matcher = pattern.matcher(text);

                if (matcher.find()) {
                    // 提取数字部分
                    String numberStr = matcher.group(1);
                    try {
                        int number = Integer.parseInt(numberStr);
                        int newNumber = number + 1;
                        String newNumberStr = String.format("%03d", newNumber); // 保持3位数字，前面补零

                        // 构建新的文本
                        String newText = text.replaceFirst(
                                "新干人事调干字\\(2025\\)第" + numberStr + "号",
                                "新干人事调干字(2025)第" + newNumberStr + "号"
                        );

                        // 清除原有内容并添加新内容
                        for (int i = para.getRuns().size() - 1; i >= 0; i--) {
                            para.removeRun(i);
                        }
                        XWPFRun run = para.createRun();
                        run.setText(newText);

                        modified = true;
                        System.out.println("找到并修改: " + text + " -> " + newText);

                    } catch (NumberFormatException e) {
                        System.err.println("无法解析数字: " + numberStr);
                    }
                }
            }

            // 在表格中查找并修改
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph para : cell.getParagraphs()) {
                            String text = para.getText();
                            Matcher matcher = pattern.matcher(text);

                            if (matcher.find()) {
                                // 提取数字部分
                                String numberStr = matcher.group(1);
                                try {
                                    int number = Integer.parseInt(numberStr);
                                    int newNumber = number + 1;
                                    String newNumberStr = String.format("%03d", newNumber);

                                    // 构建新的文本
                                    String newText = text.replaceFirst(
                                            "新干人事调干字\\(2025\\)第" + numberStr + "号",
                                            "新干人事调干字(2025)第" + newNumberStr + "号"
                                    );

                                    // 清除原有内容并添加新内容
                                    for (int i = para.getRuns().size() - 1; i >= 0; i--) {
                                        para.removeRun(i);
                                    }
                                    XWPFRun run = para.createRun();
                                    run.setText(newText);

                                    modified = true;
                                    System.out.println("找到并修改: " + text + " -> " + newText);

                                } catch (NumberFormatException e) {
                                    System.err.println("无法解析数字: " + numberStr);
                                }
                            }
                        }
                    }
                }
            }

            if (modified) {
                // 保存修改后的文档
                try (FileOutputStream out = new FileOutputStream(filePath)) {
                    document.write(out);
                    System.out.println("文档修改成功: " + filePath);
                }
            } else {
                System.out.println("未找到匹配的文本模式");
            }
        }
    }

    /**
     * 专门用于处理人事调干字号的方法
     * @param filePath 文档路径
     */
    public static void incrementPersonnelDocumentNumber(String filePath) {
        // 正则表达式：匹配 "新干人事调干字（2025）第080号" 这样的格式，并提取数字部分
        String pattern = "新干人事调干字\\(2025\\)第(\\d{3})号";
        incrementNumberInPattern(filePath, pattern);
    }

    /**
     * 查找文档中所有匹配指定模式的内容
     * @param filePath 文档路径
     * @param pattern 正则表达式模式
     * @return 匹配的内容列表
     */
    public static java.util.List<String> findPatternInDocument(String filePath, String pattern) {
        java.util.List<String> matches = new java.util.ArrayList<>();

        try {
            if (isDocxFormat(filePath)) {
                try (FileInputStream fis = new FileInputStream(filePath);
                     XWPFDocument document = new XWPFDocument(fis)) {

                    Pattern regexPattern = Pattern.compile(pattern);

                    // 在段落中查找
                    for (XWPFParagraph para : document.getParagraphs()) {
                        String text = para.getText();
                        Matcher matcher = regexPattern.matcher(text);
                        while (matcher.find()) {
                            matches.add(matcher.group());
                        }
                    }

                    // 在表格中查找
                    for (XWPFTable table : document.getTables()) {
                        for (XWPFTableRow row : table.getRows()) {
                            for (XWPFTableCell cell : row.getTableCells()) {
                                for (XWPFParagraph para : cell.getParagraphs()) {
                                    String text = para.getText();
                                    Matcher matcher = regexPattern.matcher(text);
                                    while (matcher.find()) {
                                        matches.add(matcher.group());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("查找模式时出错: " + e.getMessage());
            e.printStackTrace();
        }

        return matches;
    }

    public static boolean isDocxFormat(String filePath) {
        return filePath.toLowerCase().endsWith(".docx");
    }
}
